#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h> 
#include <sys/time.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("usage : %s <port> \n", argv[0]);
        return 0;
    }
    int serv_sock = socket(PF_INET, SOCK_STREAM, 0);
    // address
    struct sockaddr_in serv_addr, client_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(atoi(argv[1]));

   
    if (bind(serv_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
        error_handling("bind() error");
    if (listen(serv_sock, 5) == -1)
        error_handling("listen() error");
   
    fd_set fs, tmp;
    FD_ZERO(&fs);
    FD_SET(serv_sock, &fs);
    // 开始时数量为serv_sock
    int fd_max = serv_sock;
    struct timeval timeout;
    char buf[BUFSIZE];

    while (1) {
        tmp = fs;
        timeout.tv_sec = 5;
        timeout.tv_usec = 5000;

        int fd_num = select(fd_max + 1, &tmp, 0, 0, &timeout);
        printf("fd_num = %d\n", fd_num);
        if (fd_num == -1) {
            break;
        } else if (fd_num == 0) {
            continue;
        } else {
            for (int i = 0; i <= fd_max; i++) {
                if (FD_ISSET(i, &tmp)) {
                    // 监听事件
                    if (i == serv_sock) {
                        int addr_size = sizeof(client_addr);
                        int connfd = accept(serv_sock,  (struct sockaddr *)&client_addr, &addr_size);
                        FD_SET(connfd, &fs);
                        printf("connfd = %d\n", connfd);
                        if (fd_max < connfd)
                            fd_max = connfd;
                        printf("conneted client: %d \n", connfd);
                    } else {
                        // 读写事件
                        int str_len = read(i, buf, BUFSIZE);
                        if (str_len == 0) {
                            FD_CLR(i, &fs);
                            close(i);
                            printf("closed client: %d \n", i);
                        } else {
                            // echo
                            write(i, buf, str_len);
                        }
                    }
                }
            }
        }
        
    }
    close(serv_sock);
    return 0;
}